#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ManageMyself MySQL API 测试脚本
测试后端API服务与MySQL数据库的连接
"""

import requests
import json
import time
from datetime import datetime

# API 基础URL
BASE_URL = "http://localhost:8080/api"

def print_header(title):
    """打印测试标题"""
    print("\n" + "="*50)
    print(f"  {title}")
    print("="*50)

def test_health_check():
    """测试健康检查接口"""
    print_header("健康检查测试")
    
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=10)
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print("✅ API服务正常运行")
            print(f"应用状态: {data.get('status')}")
            print(f"数据库状态: {data.get('database')}")
            print(f"时间戳: {data.get('timestamp')}")
            return True
        else:
            print("❌ API服务异常")
            print(f"响应: {response.text}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 连接失败: {e}")
        return False

def test_database_status():
    """测试数据库状态"""
    print_header("数据库状态测试")
    
    try:
        response = requests.get(f"{BASE_URL}/db-status", timeout=10)
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print("✅ 数据库连接正常")
            print(f"数据库类型: {data.get('database')}")
            print(f"连接状态: {data.get('status')}")
            if 'url' in data:
                print(f"数据库URL: {data.get('url')}")
            if 'driver' in data:
                print(f"驱动程序: {data.get('driver')}")
            if 'version' in data:
                print(f"数据库版本: {data.get('version')}")
            return True
        else:
            print("❌ 数据库连接异常")
            print(f"响应: {response.text}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return False

def test_user_login():
    """测试用户登录"""
    print_header("用户登录测试")
    
    # 测试管理员登录
    login_data = {
        "username": "admin",
        "password": "admin123"
    }
    
    try:
        response = requests.post(f"{BASE_URL}/users/login", 
                               json=login_data, 
                               headers={'Content-Type': 'application/json'},
                               timeout=10)
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print("✅ 管理员登录成功")
            print(f"用户ID: {data.get('user', {}).get('id')}")
            print(f"用户名: {data.get('user', {}).get('username')}")
            print(f"角色: {data.get('user', {}).get('role')}")
            return data.get('user', {})
        else:
            print("❌ 登录失败")
            print(f"响应: {response.text}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return None

def test_user_registration():
    """测试用户注册"""
    print_header("用户注册测试")
    
    # 生成唯一用户名
    timestamp = int(time.time())
    register_data = {
        "username": f"testuser{timestamp}",
        "password": "test123456",
        "email": f"test{timestamp}@example.com",
        "fullName": "测试用户"
    }
    
    try:
        response = requests.post(f"{BASE_URL}/users/register", 
                               json=register_data, 
                               headers={'Content-Type': 'application/json'},
                               timeout=10)
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 201:
            data = response.json()
            print("✅ 用户注册成功")
            print(f"用户ID: {data.get('user', {}).get('id')}")
            print(f"用户名: {data.get('user', {}).get('username')}")
            print(f"邮箱: {data.get('user', {}).get('email')}")
            return data.get('user', {})
        else:
            print("❌ 注册失败")
            print(f"响应: {response.text}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return None

def test_task_operations(user_id):
    """测试任务操作"""
    print_header("任务操作测试")
    
    if not user_id:
        print("❌ 无效的用户ID，跳过任务测试")
        return
    
    # 创建任务
    task_data = {
        "title": "API测试任务",
        "description": "这是一个通过API创建的测试任务",
        "userId": user_id,
        "priority": "HIGH",
        "dueDate": "2024-12-31T23:59:59"
    }
    
    try:
        # 创建任务
        response = requests.post(f"{BASE_URL}/tasks", 
                               json=task_data, 
                               headers={'Content-Type': 'application/json'},
                               timeout=10)
        
        print(f"创建任务状态码: {response.status_code}")
        
        if response.status_code == 201:
            task = response.json()
            task_id = task.get('id')
            print("✅ 任务创建成功")
            print(f"任务ID: {task_id}")
            print(f"任务标题: {task.get('title')}")
            print(f"任务状态: {task.get('status')}")
            
            # 获取用户任务列表
            response = requests.get(f"{BASE_URL}/tasks/user/{user_id}", timeout=10)
            if response.status_code == 200:
                tasks = response.json()
                print(f"✅ 获取任务列表成功，共 {len(tasks)} 个任务")
            
            return task_id
        else:
            print("❌ 任务创建失败")
            print(f"响应: {response.text}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return None

def test_api_info():
    """测试API信息接口"""
    print_header("API信息测试")
    
    try:
        response = requests.get(f"{BASE_URL}/info", timeout=10)
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            data = response.json()
            print("✅ API信息获取成功")
            print(f"应用名称: {data.get('application')}")
            print(f"版本: {data.get('version')}")
            print(f"描述: {data.get('description')}")
            print(f"数据库: {data.get('database')}")
            print(f"框架: {data.get('framework')}")
            print(f"Java版本: {data.get('java')}")
            
            endpoints = data.get('endpoints', {})
            print("\n可用端点:")
            for name, path in endpoints.items():
                print(f"  {name}: {path}")
            
            return True
        else:
            print("❌ API信息获取失败")
            print(f"响应: {response.text}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
        return False

def main():
    """主测试函数"""
    print("ManageMyself MySQL API 测试开始")
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"API地址: {BASE_URL}")
    
    # 测试计数
    total_tests = 0
    passed_tests = 0
    
    # 1. 健康检查测试
    total_tests += 1
    if test_health_check():
        passed_tests += 1
    
    # 2. 数据库状态测试
    total_tests += 1
    if test_database_status():
        passed_tests += 1
    
    # 3. API信息测试
    total_tests += 1
    if test_api_info():
        passed_tests += 1
    
    # 4. 用户登录测试
    total_tests += 1
    admin_user = test_user_login()
    if admin_user:
        passed_tests += 1
    
    # 5. 用户注册测试
    total_tests += 1
    new_user = test_user_registration()
    if new_user:
        passed_tests += 1
    
    # 6. 任务操作测试
    total_tests += 1
    user_id = new_user.get('id') if new_user else admin_user.get('id') if admin_user else None
    if test_task_operations(user_id):
        passed_tests += 1
    
    # 测试总结
    print_header("测试总结")
    print(f"总测试数: {total_tests}")
    print(f"通过测试: {passed_tests}")
    print(f"失败测试: {total_tests - passed_tests}")
    print(f"成功率: {(passed_tests/total_tests)*100:.1f}%")
    
    if passed_tests == total_tests:
        print("\n🎉 所有测试通过！MySQL API服务运行正常！")
    else:
        print(f"\n⚠️  有 {total_tests - passed_tests} 个测试失败，请检查服务状态")

if __name__ == "__main__":
    main() 